package com.example.choupaiapp.main.activity.mine;

import android.Manifest;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.bumptech.glide.Glide;
import com.example.choupaiapp.R;
import com.example.choupaiapp.common.constant.Contacts;
import com.example.choupaiapp.common.finalokgo.callback.Callback;
import com.example.choupaiapp.common.finalokgo.request.RequestType;
import com.example.choupaiapp.common.ui.activity.CommonActivity;
import com.example.choupaiapp.common.util.DialogUtil;
import com.example.choupaiapp.common.util.Utils;
import com.example.choupaiapp.main.bean.SendCodeBean;
import com.example.choupaiapp.main.bean.TokenBean;
import com.example.choupaiapp.main.callback.RedBookPresenter;
import com.example.choupaiapp.main.constant.Config;
import com.example.choupaiapp.main.constant.Url;
import com.lzy.okgo.model.Response;
import com.qiniu.android.storage.Configuration;
import com.qiniu.android.storage.UploadManager;
import com.ypx.imagepicker.ImagePicker;
import com.ypx.imagepicker.bean.ImageItem;
import com.ypx.imagepicker.bean.MimeType;
import com.ypx.imagepicker.bean.PickerError;
import com.ypx.imagepicker.data.OnImagePickCompleteListener;
import com.ypx.imagepicker.data.OnImagePickCompleteListener2;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Random;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by ASUS on 2019/11/19.
 */

public class MineBgActivity extends CommonActivity {

    @BindView(R.id.bg)
    ImageView bg;
    private String bgUrl;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mine_bg);
    }

    @Override
    protected void initView() {
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            setTitle(bundle.getString("name"));
            bgUrl = bundle.getString("url");
            Glide.with(context)
                    .load(bgUrl + Config.IMAGE_LIM)
                    .centerCrop()
                    .into(bg);
        }

    }

    @Override
    protected void initData() {

    }

    @OnClick(R.id.change_bg)
    public void onViewClicked() {
        if (Utils.isDoubleClick()) {
            return;
        }
        if (rxPermissions.isGranted(Manifest.permission.CAMERA)) {
            if (rxPermissions.isGranted(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                showTakePhoto();
            } else {
                rxPermissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE).subscribe(aBoolean -> {
                    if (aBoolean) {
                        showTakePhoto();
                    } else {
                        showToast("拒绝权限可能导致功能不能正常使用");
                    }
                });
            }

        } else {
            rxPermissions.request(Manifest.permission.CAMERA).subscribe(aBoolean -> {
                if (aBoolean) {
                    if (rxPermissions.isGranted(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                        showTakePhoto();
                    } else {
                        rxPermissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE).subscribe(aBoolean1 -> {
                            if (aBoolean1) {
                                showTakePhoto();
                            } else {
                                showToast("拒绝权限可能导致功能不能正常使用");
                            }
                        });
                    }
                } else {
                    showToast("拒绝权限可能导致功能不能正常使用");
                }
            });
        }

    }

    private void showTakePhoto() {
        DialogUtil.getInstance().showBottomDialog(this, R.layout.dialog_add_photo);
        LinearLayout dialog_bottom_layout = (LinearLayout) DialogUtil.getInstance().dialog_bottom_layout;

        dialog_bottom_layout.findViewById(R.id.ablum).setOnClickListener(view -> {
            if (Utils.isDoubleClick()) {
                return;
            }
            DialogUtil.getInstance().dialog_bottom.dismiss();
            ImagePicker.withCrop(new RedBookPresenter())//设置presenter
                    .setMaxCount(1)//设置选择数量
                    .showCamera(false)//设置显示拍照
                    .setColumnCount(4)//设置列数
                    .mimeTypes(MimeType.ofImage())//设置需要加载的文件类型
                    .pick(MineBgActivity.this, new OnImagePickCompleteListener2() {
                        @Override
                        public void onPickFailed(PickerError error) {

                        }

                        @Override
                        public void onImagePickComplete(ArrayList<ImageItem> items) {
                            //图片剪裁回调，主线程
                            //注意：剪裁回调里的ImageItem中getCropUrl()才是剪裁过后的图片地址
                            Glide.with(context).load(items.get(0).getPath()).centerCrop().into(bg);
                            updateBg(items.get(0).getPath());
                        }

                    });
        });

        dialog_bottom_layout.findViewById(R.id.take_photo).setOnClickListener(view -> {
            if (Utils.isDoubleClick()) {
                return;
            }
            DialogUtil.getInstance().dialog_bottom.dismiss();
            ImagePicker.takePhoto(MineBgActivity.this, "cp_" + System.currentTimeMillis(), true, new OnImagePickCompleteListener() {
                @Override
                public void onImagePickComplete(ArrayList<ImageItem> items) {
                    Glide.with(context).load(items.get(0).getPath()).centerCrop().into(bg);
                    updateBg(items.get(0).getPath());

                }
            });

        });

        dialog_bottom_layout.findViewById(R.id.cancel).setOnClickListener(view -> DialogUtil.getInstance().dialog_bottom.dismiss());
    }

    private void updateBg(String path) {
        showDialog(context, "修改中...");

        finalOkGo.requestHead(RequestType.POSTHEAD, Url.GET_QINIU_TOKEN, null, Url.GET_QINIU_TOKEN, new Callback<TokenBean>() {
            @Override
            public void onSuccess(TokenBean tokenBean) {
                if (tokenBean.getCode() == Contacts.SUCCESS) {
                    Configuration config = new Configuration.Builder()
                            .build();
                    // 重用uploadManager。一般地，只需要创建一个uploadManager对象
                    UploadManager uploadManager = new UploadManager(config);//配置3个线程数并发上传；不配置默认为3，只针对file.size>4M生效。线程数建议不超过5，上传速度主要取决于上行带宽，带宽很小的情况单线程和多线程没有区别

                    String keyName = System.currentTimeMillis() + "" + (new Random().nextInt(999999) + 100000) + path.substring(path.lastIndexOf("."));

                    uploadManager.put(path, keyName, tokenBean.getToken(), (key, info, response) -> {
                        //res包含hash、key等信息，具体字段取决于上传策略的设置
                        if (info.isOK()) {
                            JSONObject jsonObject = new JSONObject();
                            try {
                                jsonObject.put("backgroundImg", Url.QINIU_YUN + key);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            finalOkGo.requestHead(RequestType.POSTJSONHEAD, Url.CHANGE_USERINFO, null, jsonObject.toString(), new Callback<SendCodeBean>() {
                                @Override
                                public void onSuccess(SendCodeBean sendCodeBean) {
                                    dismissDialog();
                                    if (sendCodeBean.getCode() == Contacts.SUCCESS) {
                                        EventBus.getDefault().post("refresh_mine");
                                        finishActivity();
                                    } else {
                                        if (sendCodeBean.getCode() == Contacts.TOKEN_EMPTY) {
                                        } else {
                                            showImageToas(sendCodeBean.getMsg());
                                        }
                                    }
                                }

                                @Override
                                public void onError(Response<String> response) {
                                    super.onError(response);
                                    dismissDialog();
                                }
                            });
                        } else {
                            //如果失败，这里可以把info信息上报自己的服务器，便于后面分析上传错误原因
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    showImageToas(info.error);
                                }
                            });
                        }
                    }, null);
                } else {
                    if (tokenBean.getCode() == Contacts.TOKEN_EMPTY) {
                    } else {
                        showImageToas(tokenBean.getMsg());
                    }
                }
            }
        });

    }
}
